package com.test.lol;

import java.io.IOException;

import android.app.Activity;
import android.database.Cursor;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class Exif{

	
	
    public String getExif(Activity parent, Uri uri){
    	
    	String exifFilePath;
        String[] proj = { MediaStore.Images.Media.DATA };
        String gpsJson;
        Cursor cursor = parent.managedQuery(uri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        exifFilePath = cursor.getString(column_index);
        
    	try {
    		ExifInterface exifInterface = new ExifInterface(exifFilePath);
    		String longitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
    		String latitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
    		String longitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
    		String latitudeRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
    		gpsJson = convertGPSToDegree(longitude, longitudeRef, latitude, latitudeRef);
			Log.v(this.getClass().getName(), uri.toString() + "    " + gpsJson);
		} catch (IOException e) {
			gpsJson = "ERROR";
			e.printStackTrace();
		}
    	Log.v(this.getClass().getName(),"RETURN: " + gpsJson);
    	return gpsJson;
    }
    
    private String convertGPSToDegree(String longitude, String longitudeRef, String latitude, String latitudeRef){
    	
    	
    	 if((latitude !=null)
    	   && (latitudeRef !=null)
    	   && (longitude != null)
    	   && (longitudeRef !=null))
    	 {

    	  if(latitudeRef.equals("N")){
    	   latitude = convertToDegree(latitude);
    	  }
    	  else{
    	   latitude = "-"+convertToDegree(latitude);
    	  }
    	 
    	  if(longitudeRef.equals("E")){
    	   longitude = convertToDegree(longitude);
    	  }
    	  else{
    		  longitude = "-"+convertToDegree(longitude);
    	  }
    	 
    	 }
    	return "'longitude':'"+longitude+"', 'latitude':'"+latitude+"'";
    }
    
    private String convertToDegree(String stringDMS){
    	 Float result = null;
    	 String[] DMS = stringDMS.split(",", 3);

    	 String[] stringD = DMS[0].split("/", 2);
    	    Double D0 = new Double(stringD[0]);
    	    Double D1 = new Double(stringD[1]);
    	    Double FloatD = D0/D1;

    	 String[] stringM = DMS[1].split("/", 2);
    	 Double M0 = new Double(stringM[0]);
    	 Double M1 = new Double(stringM[1]);
    	 Double FloatM = M0/M1;
    	  
    	 String[] stringS = DMS[2].split("/", 2);
    	 Double S0 = new Double(stringS[0]);
    	 Double S1 = new Double(stringS[1]);
    	 Double FloatS = S0/S1;
    	  
    	    result = new Float(FloatD + (FloatM/60) + (FloatS/3600));
    	  
    	 return result+"";


    	}
    
}
